﻿using System;
using System.Collections.Generic;
using System.Text;
using DBScript;
using eBlog.Entity;
using eBlog.Cache;

namespace eBlog.Service
{
   public class TermsService
    {


       /// <summary>
       /// add terms, both  type and tags
       /// </summary>
       /// <param name="terms">terms'model</param>
       /// <returns>index of the new model int db</returns>
       public static int AddTerms(Terms terms)
       {
           IDBBase dal = DBFactory.GetDbProvider();
           return dal.Add(terms);
       }

       public static Terms GetTerms(int termsId)
       {
           if(CacheService<Terms>.IsCacheExist(termsId.ToString()))
           {
               return CacheService<Terms>.GetCacheItem(termsId.ToString());
           }
           else
           {
               IDBBase dal = DBFactory.GetDbProvider();

               Terms terms= dal.GetModel<Terms>(termsId);

               if(terms!=null)
               {
                   CacheService<Terms>.AddCache(terms,terms.ID.ToString());
               }

               return terms;
           }


          
       }

       /// <summary>
        /// get posts type list
        /// </summary>
        /// <returns>posts type list</returns>
       public static List<Terms> GetPostsTypeList()
        {
            IDBBase dal = DBFactory.GetDbProvider();
            List<Terms> lists = dal.Where("Type=1").GetList<Terms>();
            return lists;
        }


       /// <summary>
       /// get post tags list
       /// </summary>
       /// <returns> posts tag list</returns>
       public static List<Terms> GetPostsTagsList(int? count=null)
       {
           IDBBase dal = DBFactory.GetDbProvider();

           return count.HasValue ? dal.Where("Type=2").LimitLengh(count.Value).GetList<Terms>() : dal.Where("Type=1").GetList<Terms>();
       }
       /// <summary>
       /// get post's tags
       /// </summary>
       /// <param name="postId"></param>
       /// <returns></returns>
       public static List<Terms> GetPostTagsList(int postId)
       {
           IDBBase dal = DBFactory.GetDbProvider();
           Posts posts = dal.GetModel<Posts>(postId);
           List<Terms> list=new List<Terms>();

           if (posts!=null)
           {
               list = dal.Where("ID in ("+posts.Tag+")").GetList<Terms>();
           }

           return list;
       }
    }
}
